import axios from "axios";
import router from "@/router/index";
import { loginOut } from "../assets/js/utils";
import { ElLoading } from "element-plus";

// 创建全局loading实例
let loadingInstance = null;
// axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
export const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASEURL,
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 针对特定接口开启全局loading
    if (config.url === "/operation/multiOperation") {
      loadingInstance = ElLoading.service({
        lock: true,
        text: "加载中，请稍候...",
        background: "rgba(0, 0, 0, 0.7)",
      });
    }
    let token = localStorage.getItem("token");
    if (token) {
      config.headers["sso_token"] = token;
    }
    return config;
  },
  (err) => {
    ElMessage.error(err.message);
  }
);

let isLogin = true;
/// 响应拦截器
service.interceptors.response.use(
  (res) => {
    if (loadingInstance) {
      loadingInstance.close();
    }
    let data = res;
    if (data.data.code == 903 && res.config.url != "/operation/getAutoAddLightStatus") {
      ElMessage.error(data.data.message);
    }
    if (data.status == 800) {
      if (isLogin) {
        isLogin = false;
        ElMessageBox.confirm("登录已失效，请重新登录？", "提示", {
          showClose: false,
          showCancelButton: false,
        })
          .then(() => {
            isLogin = true;
            loginOut();
          })
          .catch(() => {
            isLogin = true;
          });
      }
    } else if (data.status == 9999) {
      ElMessage.error(data.message);
      setTimeout(function () {
        loginOut();
      }, 1000);
    } else if (data.status != 200) {
      ElMessage.error(data.message);
    } else if (data.status === 200) {
      if (data.data.code === 400) {
        ElMessage.error(`CODE:${data.data.code}->提示信息:${data.data.message}`);
      }
    }
    return res;
  },
  (err) => {
    if (loadingInstance) {
      loadingInstance.close();
    }
    if (err.response == undefined) {
      router.push("/login");
      return;
    } else {
      switch (err.response.status) {
        case 404:
          ElMessage.error("请求地址错误!");
          break;
        case 400:
          ElMessage.error("客户端请求有语法错误，不能被服务器所理解");
          break;
        case 403:
          router.push("/login");
          localStorage.removeItem("info");
          break;
        case 503:
          ElMessage.error("系统更新中,请稍等!");
          break;
        case 504:

        case 505:

        case 500:
          ElMessage.error("CODE:500,系统请求异常");
          break;

        default:
          ElMessage.error({ message: "未知错误!" });
      }
    }
    return err;
  }
);

let get = (url, params = {}) => {
  return new Promise((resolve, reject) => {
    service
      .get(url, {
        params,
      })
      .then((res) => {
        if (res) {
          if (res.status == 200) {
            resolve(res);
          } else {
            reject(res);
          }
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
};

let post = (url, data = {}, header = {}) => {
  return new Promise((resolve, reject) => {
    service
      .post(url, data, header)
      .then((res) => {
        if (res) {
          if (res.status == 200) {
            resolve(res);
          } else {
            reject(res);
          }
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
};

export const $axios = {
  get,
  post,
};
